package icu.sunway.gushenBlogBackEnd.Service.Implement;

import icu.sunway.gushenBlogBackEnd.Entity.View.ResultVO;
import icu.sunway.gushenBlogBackEnd.Message.MailMessage;
import icu.sunway.gushenBlogBackEnd.Service.MailService;
import icu.sunway.gushenBlogBackEnd.utils.VerifyCodeGenerator;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.time.Duration;
import java.util.Objects;

@Service
public class MailServiceImpl implements MailService {

    @Value("${spring.mail.username}")
    private String from;

    private final JavaMailSender mailSender;
    private final RedisTemplate<String, Object> redisTemplate;

    public MailServiceImpl(JavaMailSender mailSender, RedisTemplate<String, Object> redisTemplate) {
        this.mailSender = mailSender;
        this.redisTemplate = redisTemplate;
    }


    @Override
    public void sendSimpleMail(String to, String title, String content) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, false);
            helper.setFrom(from, "GushenBlog");
            helper.setTo(to);
            helper.setSubject(title);
            helper.setText(content, true);
            mailSender.send(message);
        } catch (MessagingException | UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ResultVO<Boolean> sendVerifyCode(String to) {
        try {
            String verifyCode = VerifyCodeGenerator.generateVerifyCode();
            redisTemplate.opsForValue().set("verifyCode_" + to, verifyCode);
            redisTemplate.expire("verifyCode_" + to, Duration.ofMinutes(5));
            sendSimpleMail(to, "GushenBlog注册验证码", "您的验证码是 <strong>" + verifyCode + "</strong>");
            return new ResultVO<>(200, MailMessage.send_success, true);
        } catch (Exception e) {
            return new ResultVO<>(400, MailMessage.send_fail, false);
        }
    }

    @Override
    public Boolean checkVerifyCode(String to, String toBeCheckedCode) {
        if (Boolean.TRUE.equals(redisTemplate.hasKey("verifyCode_" + to))) {
            String verifyCode = Objects.requireNonNull(redisTemplate.opsForValue().get("verifyCode_" + to)).toString();
            return verifyCode.equals(toBeCheckedCode);
        }
        return false;
    }
}
